<?php
include("header.inc.php");
?>

<?php

/* Connect to database */
include("db.inc.php");
$con = mysql_connect(MYSQL_HOST,MYSQL_USER,MYSQL_PASSWORD);

if (!$con) {
         die ('Error: Could not connect to mySQL server');
}
$mysql = MYSQL_DB;
if (!mysql_select_db($mysql)) {
        die ('Error: Could not connect to mySQL database');
}


/* Get table name from URL */
$tableName = $_GET["data"];



/* Make sure table exist in database */
if ($tableName != "" && /*$tableName != "users" &&*/ $tableName !="access_levels") {
// Solution from http://stackoverflow.com/questions/1525784/mysql-check-if-a-table-exists-without-throwing-an-exception 
$result = mysql_query("SHOW TABLES LIKE '$tableName'");
$tableExists = mysql_num_rows($result) > 0;
if (!$tableExists) {
	echo "<p>The table you have requested (\"" . $_GET["data"] . "\") does not exist.</p>";
}
} else {
$tableExits = 0;
}


echo "<h2>Edit Data</h2>";



// If table exists 
if ($tableExists) { //START MASTER IF


/* Get values from POST for Edit*/
if ($_POST['DeleteSelected']!='Delete Selected') {
while (list($key, $value) = each($_POST)) {
	if (substr($key, 0, 5)=='edit_' && $value == 'Edit') {
		$_POST['EditSelected'] = 'Edit';
		$_POST['edit_'] = substr($key, 5);
	} else if (substr($key, 0, 7)=='delete_') {
		continue;
	} else {
		break;
	}
}
}



/* Input forms */
$result = mysql_query("SELECT * FROM $tableName");
$fields = mysql_num_fields($result);
if ($_POST['EditSelected']=='Edit') {
	$result = mysql_query("SELECT * FROM $tableName WHERE " . mysql_field_name($result, 0) . "='" . $_POST['edit_'] . "'");
	$row = mysql_fetch_array($result);
}

if ($_POST['Submit']=='Plain Text Input' || $_POST['Submit']=='Plain Text Edit') {
        $_GET['input'] = "plain";
} else if ($_POST['Submit']=='Form Input' || $_POST['Submit']=='Form Edit') {
        $_GET['input'] = "";
}


echo "<form action='editData.php?data=$tableName&input=" . $_GET['input'] ."' method='post'>\n";
echo "<h3>$tableName</h3>\n";
echo "<div class='sub-navigation'>";
if ($_POST['EditSelected']=='Edit' || $_POST['Submit']=='Plain Text Edit' || $_POST['Submit']=='Form Edit') {
	echo "<input name='Submit'";
	if ($_GET['input'] != "plain") {
		echo " class='selected'";
	}	
	echo " value='Form Edit' type='Submit' />\n";
	echo "<input name='Submit'";
        if ($_GET['input'] == "plain") {
                echo " class='selected'";
        }
	echo " value='Plain Text Edit' type='Submit' />\n";
} else {
	echo "<input name='Submit'";
        if ($_GET['input'] != "plain") {
		echo " class='selected'";
	}
	echo " value='Form Input' type='Submit' />\n";
	echo "<input name='Submit'";
	if ($_GET['input']=="plain") {
		echo " class='selected'";
	}
	echo " value='Plain Text Input' type='Submit' />\n";
}
echo "</div>\n";


/* Parse values from Plain Text input*/
if ($_POST['plain_text']!="") {
        $plain = preg_split("/[\n]+/", $_POST['plain_text'], -1, PREG_SPLIT_NO_EMPTY);
} else {
 for ($i=0; $i < $fields; $i++) {
        $name  = mysql_field_name($result, $i);
        $name = "aed_" . $name;
        $plain[$i] = $_POST[$name];
 }
}
/* Validate */
if ($_POST['Submit']=='Add Data' || $_POST['Submit']=='Make Copy' || $_POST['EditSelected']=='Update Data') {
 for ($i=0; $i < $fields; $i++) {
  /* Replacing bad things */
  $plain[$i] = str_replace("\\", "&#92;", $plain[$i]);
  $plain[$i] = str_replace("'", "&#39;", $plain[$i]);


 }
}



/* Plain text method of input */
if ($_GET["input"]=="plain") {
echo "<table class=\"plain-input\">\n";
echo "<tr><td>";
for ($i=0; $i < $fields; $i++) {
        echo mysql_field_name($result, $i) . "<br />";
}
echo "</td>\n<td><textarea name=\"plain_text\" rows=\"" . ($fields) ."\"";
echo " cols=\"60\">";
for ($i=0; $i < $fields; $i++) {
	if ($_POST['EditSelected']=='Edit') {
		$name = mysql_field_name($result, $i);
		echo "\n" .$row[$name];
	} else if ($_POST['Submit']=='Plain Text Input' || $_POST['Submit']=='Plain Text Edit') {
		echo "\n". $plain[$i];
		
	} else {
		echo "\n";
	}
}
echo "</textarea></td></tr>\n";
echo "</table><br />\n\n";




/* Forms input */
} else {
echo "<table class=\"input\">\n";
	for ($i=0; $i < $fields; $i++) {
		if ($i % 2 == 0) {
			if ($i != 0) {
				echo "</tr>\n";
			}
			echo "<tr>";
		}
		$name  = mysql_field_name($result, $i);
		echo "<td>" . $name . "</td>\n<td";
		if ($i % 2 == 0) {
			echo " class='first-col'";
		}
		echo "><input type='text' name='aed_" . $name . "' ";
		if ($_POST['EditSelected']=='Edit') {
			echo "value ='" . $row[$name] . "' ></td>\n";
		} else if ($_POST['Submit']=='Form Input' || $_POST['Submit']=='Form Edit') {
			echo "value = '" . $plain[$i] . "' ></td>\n";
		} 
		else {
			echo "/></td>\n";
		}
	}
	if ($field % 2 == 0) {
		echo "</tr>\n";
	} else echo "<td></td><td></td><tr>\n";
		echo "</table>\n";
}
if ($_POST['EditSelected']=='Edit' || $_POST['Submit']=='Plain Text Edit' || $_POST['Submit']=='Form Edit') {
	echo "<input name='EditSelected' value='Update Data' type='Submit' />\n";
	echo "<input name='Submit' value='Make Copy' type='Submit' />\n";
} else {
	echo "<input name='Submit' value='Add Data' type='Submit' />\n";
}
echo "</form>\n";






/* INSERT VALUES INTO DATABASE */
if (count($_POST)!=0 && $_POST['Submit']=='Add Data' || $_POST['Submit']=='Make Copy') { 
echo "<p>Adding...\n";
/* Building sql String */
$sql = "INSERT INTO $tableName (";
for ($i=0; $i < $fields; $i++) {
	if ($i!=0) {
		$sql = $sql . ", ";
	}
	$name  = mysql_field_name($result, $i);
	$sql = $sql . $name;
}
$sql = $sql . ") VALUES (";
for ($i=0; $i < $fields; $i++) {
        if ($i!=0) {
                $sql = $sql . ", ";
        }
	$sql = $sql . "'" . $plain[$i] . "'";
}
$sql = $sql . ")";
//echo $sql . "<br />\n";
if (!mysql_query($sql,$con))
  {
  echo "Error: There is an error...Unable to add data!</p>\n";
  echo "<p>Error: " . mysql_error() . "</p>";
  }
else echo "Data saved!</p>\n";
}
/* Note on PHP characters */
//http://stackoverflow.com/questions/68651/can-i-get-php-to-stop-replacing-characters-in-get-or-post-arrays





/* DELETE VALUES FROM DATABASE */
else if (count($_POST)!=0 && $_POST['DeleteSelected']=='Delete Selected') {
/* !!!!!!!!!!!!!!!!!!PROTOTYPE IS CURRENTLY USING FIRST FIELD TO VALIDATE!!!!!!!!!!!!!!!!!!*/
/* !!!!!!!!!!!!!!!!!!ACTUAL WORKING PAGE SHOULD USE ID # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
echo "<p>Deleting...";
$name   = mysql_field_name($result, 0);
$ok	= 1;
while (list($key,$value) = each($_POST))
{
var_dump($_POST);
echo "TEST \"" . substr($key,0,7) . "\"";
	if (substr($key,0,7)=='delete_' && $value=='Yes') 
	{
		if (mysql_query("DELETE FROM $tableName WHERE " . $name . "='" . substr($key,7) . "'")) {
			echo " record with \"" . $name . "\" equal to \"" . substr($key,7) . "\",";	
		} else {
			echo "Error: There is an error...Unable to delete data!</p>\n";
			$ok = 0;
		}
	}
}
echo "...Done</p>\n";
}





/* UPDATING VALUES IN DATABASE */
else if (count($_POST)!=0 && $_POST['EditSelected']=='Update Data') {
echo"<p>Updating...";
/* !!!!!!!!!!!!!!!!!!PROTOTYPE IS CURRENTLY USING FIRST FIELD TO VALIDATE!!!!!!!!!!!!!!!!!!*/
/* !!!!!!!!!!!!!!!!!!ACTUAL WORKING PAGE SHOULD USE ID # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
$sql = "UPDATE $tableName SET "; 
for ($i=0; $i< $fields; $i++) {
	if ($i!=0) {
		$sql = $sql . ", ";
	}
	$name = mysql_field_name($result, $i);
	$sql = $sql . $name . "='" . $plain[$i] .  "'";
}
$sql = $sql . " WHERE " . mysql_field_name($result, 0) . "='" . $plain[0] . "'";
//echo "<p>$sql</p>";
if (!mysql_query($sql)) {
	echo "Error: There is an error...Unable to update data!</p>\n";
} else {
	echo "...Done</p>\n";
}
}



/* Adding consistent space between two tables */
else echo "<p><br /></p>\n";






/* GET INFO FROM DATABASE */
echo "<form action='editData.php?data=$tableName&input=" . $_GET['input'] ."' method='post'>\n";
//echo "<form></form>";
 
// Another call to get * from table is needed to show newly added/deleted record
$sql = "SELECT * FROM $tableName";
$result = mysql_query($sql, $con);
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}
//echo "<div class=\"table-display\">";
echo "<div class=\"tableContainer\">\n";
echo "<table class=\"display\">\n";

/* Headers for Display Table */
echo "<thead class=\"fixedHeader\"><tr><th></th><th></th>";
$fields = mysql_num_fields($result);
for ($i=0; $i < $fields; $i++) {
	$name  = mysql_field_name($result, $i);
	echo "<th>" . $name . "</th>";
}
echo "</tr></thead>\n";

/* Display the data */
echo "<tbody class=\"scrollContent\">\n";

while ($row = mysql_fetch_assoc($result)) {
    echo "<tr>\n";
    /* For Delete Box */
    echo "<td><input type='checkbox' name='delete_" . $row[mysql_field_name($result, 0)] . "' value='Yes' /></td>\n";
    /* For Edit Button */
    echo "<td>";
    echo "<input type='submit' name='edit_"  .  $row[mysql_field_name($result, 0)] . "' value='Edit' />";
    echo "</td>";
    /* The remainder values */
    for ($i=0; $i < $fields; $i++) {
 	echo "<td>" . $row[mysql_field_name($result, $i)] . "</td>\n";
    }
    echo "</tr>\n";
/* !!!!!!!!!!!!!!!!!!PROTOTYPE IS CURRENTLY USING FIRST FIELD NAME TO VALIDATE!!!!!!!!!!!!!!!!!!*/
/* !!!!!!!!!!!!!!!!!!ACTUAL WORKING PAGE SHOULD USE ID # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
}
echo "</tbody>\n</table>\n";
echo "</div>\n";
echo "<input type='submit' name='DeleteSelected' value='Delete Selected' />\n";
echo "</form>\n";





// Else table doesn't exist 
} else { // END MASTER IF 


// Section to print when incorrect table names are in the URL
$sql = "SHOW TABLES FROM $mysql";
$result = mysql_query($sql);
if (!$result) {
    die("DB Error, could not list tables\n");
}
echo "<p>Please select the data table you wish to edit:</p>\n";
echo "<ul>\n";
while ($row = mysql_fetch_row($result)) {
    if ($row[0]!="users" && $row[0]!="access_levels") {
    echo "<li><a title='Edit' href='editData.php?data={$row[0]}&input=" . $_GET['input'] ."'>{$row[0]}</a></li>\n";
    }
}
echo "</ul>\n";
}


/* CLOSE CONNECTION */
mysql_free_result($result);
mysql_close($con);

?>
<?php
include("footer.inc.php");
?>
